<template>
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card profile-card border-0 shadow-sm">
          <div class="card-header bg-white border-0 pb-0">
            <div class="d-flex justify-content-between align-items-center mb-3">
              <h2 class="h4 mb-0 fw-bold text-primary">个人中心</h2>
              <button 
                @click="refreshProfile" 
                type="button"
                class="btn btn-primary btn-lg d-flex align-items-center"
              >
                <i class="bi bi-arrow-repeat me-2"></i>
                刷新信息
              </button>
            </div>
          </div>
          
          <div class="card-body">
            <div class="row g-4">
              <!-- 左侧头像区域 -->
              <div class="col-lg-4 col-md-5">
                <div class="avatar-section text-center">
                  <div class="position-relative d-inline-block">
                    <div 
                      class="avatar-container rounded-circle overflow-hidden border border-3 border-light shadow-sm"
                      style="width: 160px; height: 160px;"
                    >
                      <el-upload
                        class="avatar-uploader h-100"
                        action="/api/upload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :headers="{'Authorization': tokenStore.token}"
                        drag
                      >
                        <div class="avatar-preview w-100 h-100 position-relative" @click="viewAvatar">
                          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar w-100 h-100 object-fit-cover" />
                          <div v-else class="upload-placeholder w-100 h-100 d-flex flex-column justify-content-center align-items-center bg-light">
                            <i class="bi bi-person-circle text-secondary fs-1"></i>
                            <p class="upload-text mt-2 mb-0 text-secondary small">点击上传头像</p>
                          </div>
                          <div class="overlay position-absolute top-0 start-0 w-100 h-100 d-flex justify-content-center align-items-center rounded-circle">
                            <i class="bi bi-pencil-square text-white fs-3"></i>
                          </div>
                        </div>
                      </el-upload>
                    </div>
                  </div>
                  <div class="mt-3" v-if="userInfo.avatar">
                    <button type="button" class="btn btn-outline-primary btn-sm" @click="viewAvatar">
                      <i class="bi bi-eye me-1"></i> 查看头像
                    </button>
                  </div>
                  <div class="mt-3">
                    <span :class="`badge ${userInfo.isVerified ? 'bg-success' : 'bg-warning'} fs-6`">
                      {{ userInfo.isVerified ? '已认证' : '未认证' }}
                    </span>
                  </div>
                </div>
              </div>
              
              <!-- 右侧信息区域 -->
              <div class="col-lg-8 col-md-7">
                <el-form :model="userInfo" label-width="100px" ref="userForm" :rules="formRules">
                  <div class="mb-4">
                    <label class="form-label fw-medium">用户名</label>
                    <el-form-item prop="username" class="mb-0">
                      <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                          <i class="bi bi-lock"></i>
                        </span>
                        <el-input 
                          v-model="userInfo.username" 
                          disabled
                          class="form-control border-start-0"
                        />
                      </div>
                    </el-form-item>
                  </div>
                  
                  <div class="mb-4">
                    <label class="form-label fw-medium">学号</label>
                    <el-form-item prop="studentId" class="mb-0">
                      <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                          <i class="bi bi-credit-card"></i>
                        </span>
                        <el-input 
                          v-model="userInfo.studentId" 
                          disabled
                          class="form-control border-start-0"
                        />
                      </div>
                    </el-form-item>
                  </div>
                  
                  <div class="mb-4">
                    <label class="form-label fw-medium">昵称</label>
                    <el-form-item prop="nickname" class="mb-0">
                      <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                          <i class="bi bi-person"></i>
                        </span>
                        <el-input 
                          v-model="userInfo.nickname" 
                          placeholder="请输入您的昵称" 
                          clearable
                          class="form-control border-start-0"
                        />
                      </div>
                    </el-form-item>
                  </div>
                  
                  <div class="mb-4">
                    <label class="form-label fw-medium">手机号</label>
                    <el-form-item prop="phone" class="mb-0">
                      <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                          <i class="bi bi-telephone"></i>
                        </span>
                        <el-input 
                          v-model="userInfo.phone" 
                          placeholder="请输入手机号码" 
                          clearable
                          class="form-control border-start-0"
                        />
                      </div>
                    </el-form-item>
                  </div>
                  
                  <div class="mb-4">
                    <label class="form-label fw-medium">邮箱</label>
                    <el-form-item prop="email" class="mb-0">
                      <div class="input-group">
                        <span class="input-group-text bg-light border-end-0">
                          <i class="bi bi-envelope"></i>
                        </span>
                        <el-input 
                          v-model="userInfo.email" 
                          placeholder="请输入邮箱地址" 
                          clearable
                          class="form-control border-start-0"
                        />
                      </div>
                    </el-form-item>
                  </div>
                  
                  <div class="mb-4">
                    <label class="form-label fw-medium">个人简介</label>
                    <el-form-item prop="bio" class="mb-0">
                      <el-input 
                        type="textarea" 
                        :rows="4" 
                        placeholder="请简单介绍一下自己..."
                        v-model="userInfo.bio"
                        show-word-limit
                        maxlength="200"
                        class="form-control"
                      />
                    </el-form-item>
                  </div>
                  
                  <div class="d-flex gap-2">
                    <button type="button" class="btn btn-primary px-4" @click="updateProfile" :disabled="isLoading">
                      <span v-if="isLoading" class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
                      <i class="bi bi-check-circle me-2"></i>
                      保存信息
                    </button>
                    <button type="button" class="btn btn-outline-secondary px-4" @click="resetForm">
                      <i class="bi bi-arrow-clockwise me-2"></i>
                      重置
                    </button>
                  </div>
                </el-form>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 头像查看对话框 -->
    <el-dialog
      title="查看头像"
      v-model="isAvatarDialogVisible"
      width="560px"
      :modal="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      center
    >
      <div class="avatar-dialog-container">
        <img :src="userInfo.avatar" class="avatar-dialog rounded" style="max-width: 100%; max-height: 100%;" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import useUserInfoStore from '@/stores/userInfo.js'
import { useTokenStore } from '@/stores/token.js'
import { updateUserInfoService, updateUserAvatarService } from '@/api/user.js'

// 定义响应式数据
const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()
const userInfo = reactive({
  username: '',
  nickname: '',
  studentId: '',
  isVerified: 0,
  phone: '',
  email: '',
  avatar: '',
  bio: ''
})

const userForm = ref(null)
const isLoading = ref(false)

// 表单验证规则
const formRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ]
}

// 初始化用户信息
const initUserInfo = () => {
  if (userInfoStore.info && Object.keys(userInfoStore.info).length > 0) {
    Object.assign(userInfo, userInfoStore.info)
  }
}

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传成功
const handleAvatarSuccess = (res) => {
  if (res.code === 200 || res.code === 0) {
    userInfo.avatar = res.data
    userInfoStore.info.avatar = res.data
    
    // 更新数据库中的头像
    updateUserAvatarService(res.data).then(updateRes => {
      if (updateRes.code === 200 || updateRes.code === 0) {
        ElMessage.success('头像上传成功！')
      } else {
        ElMessage.warning('头像上传成功，但数据库同步失败')
      }
    })
  } else {
    ElMessage.error('头像上传失败: ' + (res.message || '未知错误'))
  }
}

// 更新用户信息
const updateProfile = async () => {
  try {
    isLoading.value = true
    const res = await updateUserInfoService(userInfo)
    
    if (res.code === 200 || res.code === 0) {
      // 更新 store 中的用户信息
      userInfoStore.setInfo({...userInfoStore.info, ...userInfo})
      ElMessage.success('个人信息更新成功！')
    } else {
      ElMessage.error('信息更新失败: ' + (res.message || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('信息更新失败: ' + (error.message || '网络错误'))
  } finally {
    isLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  userForm.value.resetFields()
  initUserInfo()
}

// 刷新个人资料
const refreshProfile = () => {
  ElNotification({
    title: '正在刷新',
    message: '正在获取最新个人信息...',
    type: 'info',
    duration: 2000
  })
  setTimeout(() => {
    initUserInfo()
    ElMessage.success('信息已刷新')
  }, 1500)
}

// 查看头像
const isAvatarDialogVisible = ref(false)
const viewAvatar = () => {
  isAvatarDialogVisible.value = true
}

// 生命周期钩子
onMounted(() => {
  initUserInfo()
})
</script>

<style scoped>
.profile-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  overflow: hidden;
}

.profile-card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
}

.avatar-uploader {
  cursor: pointer;
  transition: all 0.3s ease;
}

.avatar-uploader:hover .overlay {
  background: rgba(0, 0, 0, 0.6);
  opacity: 1 !important;
}

.upload-placeholder {
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.avatar-uploader:hover .upload-placeholder {
  background: #e9f0ff;
}

.avatar-dialog-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

/* 添加Bootstrap样式增强 */
.form-label {
  font-weight: 500;
}

.input-group-text {
  border-color: #ced4da;
}

.form-control:focus {
  border-color: #86b7fe;
  box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}

.btn-primary {
  background-color: #0d6efd;
  border-color: #0d6efd;
}

.btn-primary:hover {
  background-color: #0b5ed7;
  border-color: #0a58ca;
}

.btn-outline-secondary {
  color: #6c757d;
  border-color: #6c757d;
}

.btn-outline-secondary:hover {
  background-color: #6c757d;
  border-color: #6c757d;
}

.badge {
  padding: 0.5em 0.75em;
}

.card {
  background-color: #fff;
  border: 1px solid rgba(0, 0, 0, 0.125);
}
</style>